const NODE_ENV = process.env.NODE_ENV;
// const NODE_ENV = 'localhost';
// const NODE_ENV = 'development';
// const NODE_ENV = 'production';

// api接口地址
const domainName = {
    // localhost: 'https://3720u56m05.oicp.vip/',
    localhost: 'http://192.168.31.186:8180/',
    // development: 'http://192.168.31.186:8180/',
    development: 'https://3720u56m05.oicp.vip/',
    production: 'https://yh-api.yiyanshenmei.com/',
}
const baseURL = domainName[NODE_ENV];

// 网页访问地址（默认为注册页面）
const registerURL = NODE_ENV == 'production' ? 'https://share-yh.yiyanshenmei.com/#/' : 'https://yh-s-test.yiyanshenmei.com/#/';


console.log("NODE_ENV:", NODE_ENV);

export default {
    NODE_ENV: NODE_ENV,
    baseURL: baseURL,
    registerURL: registerURL,

    //获取用户数据
    getUserInfo() {
        try {
            const userInfo = uni.getStorageSync('userInfo');
            if (userInfo) {
                // console.log(userInfo);
                return JSON.parse(userInfo);
            } else {
                return '';
            }
        } catch (e) {
            return ''
        }
    },
    //设置用户数据
    setUserInfo(info) {
        // alert(JSON.stringify(info));
        try {
            uni.setStorageSync('userInfo', JSON.stringify(info));
        } catch (e) {
            // error
        }
    },
    //获取用户token
    getUserToken() {
        try {
            const token = uni.getStorageSync('userToken');
            if (token) {
                // console.log(token);
                return token;
            } else {
                return '';
            }
        } catch (e) {
            return ''
        }
    },
    //设置用户token
    setUserToken(token) {
        try {
            uni.setStorageSync('userToken', token);
        } catch (e) {
            // error
        }
    },
    //清除用户数据
    clearUserInfo() {
        try {
            uni.removeStorageSync('userToken');
            uni.removeStorageSync('userInfo');
            uni.$emit('userLogout');
            setTimeout(() => {
                uni.reLaunch({
                    url: '/pages/login/login_psd'
                });
            }, 1000);
        } catch (e) {
            // error
        }
    },
    //清除所有数据
    clearAllInfo() {
        try {
            uni.clearStorageSync();
        } catch (e) {
            // error
        }
    },
    //打开新页面  url：页面路径  data：参数对象
    //示例：js中  this.$comFun.openWin('/pages/news/detail', {page: 1,num: 2})
    //      html中  @click="$comFun.openWin('/pages/news/detail', {page: 1,num: 2})"
    openWin(url, data) {
        //切换到首页、资讯列表页、我的
        // if (url == '/pages/index/index' || url == '/pages/main/mass_order' || url == '/pages/main/vol_service' || url == '/pages/main/practice' || url == '/pages/mine/index') {
        //     uni.switchTab({
        //         url: url
        //     });
        //     return;
        // }
        if (data) {
            url += (url.indexOf('?') < 0 ? '?' : '&') + this.urlParam(data)
        }
        // console.log(url);
        uni.navigateTo({
            url
        });
    },
    //关闭当前页面-打开新页面  url：页面路径  data：参数对象
    openWinTo(url, data) {
        url += (url.indexOf('?') < 0 ? '?' : '&') + this.urlParam(data)
        uni.redirectTo({
            url
        });
    },
    //关闭当前页面，回退delta个页面
    closeWin(delta) {
        delta = delta ? delta : 1;
        uni.navigateBack({
            delta: delta
        });
    },
    openLoading(txt) {
        // #ifdef APP-PLUS
        plus.nativeUI.showWaiting(txt ? txt : "等待中...", {
            background: 'rgba(0,0,0,0)',
            style: 'black',
            width: '100%',
            height: '120%',
            color: '#fff'
        });
        // #endif
        // #ifndef APP-PLUS
        uni.showLoading({
            title: '加载中'
        });
        // #endif
    },
    closeLoading() {
        // #ifdef APP-PLUS
        plus.nativeUI.closeWaiting();
        // #endif
        // #ifndef APP-PLUS
        uni.hideLoading();
        // #endif
    },
    toast(message) {
        // #ifdef APP-PLUS
        plus.nativeUI.toast(message);
        // #endif
        // #ifndef APP-PLUS
        uni.showToast({
            title: message,
            icon: 'none',
            duration: 2000
        });
        // #endif
    },
    // 打开地图
    openMap(mapData) {
        // mapData参数说明
        // const mapData = {
        //     urlAppAmap: 'sourceApplication=name&poiname=布诺林西餐厅&lat=28.723264&lon=105.069181&dev=0',//高德地图APP参数链接
        //     urlAppBmap: 'location=28.72890970607943,105.07623022035241&title=布诺林西餐厅&content=咖啡西餐厅',//百度地图APP参数链接
        //     urlAppQQmap: 'marker=coord:28.723303,105.069457;title:布诺林西餐厅;addr:咖啡西餐厅',//腾讯地图APP参数链接

        //     urlH5Amap: 'https://surl.amap.com/gQt3UbE1a9V4',//高德地图H5参数链接
        //     urlH5Bmap: 'https://j.map.baidu.com/01/SsDu',//百度地图H5参数链接
        //     urlH5QQmap: 'https://router.map.qq.com/short?l=7a5479789b6ca40c942c7aef93c14f18',//腾讯地图H5参数链接
        // };
        const that = this;

        let list = [];
        let urlList = {
            '高德地图': '',
            '百度地图': '',
            '腾讯地图': '',
        };

        // #ifdef APP-PLUS

        // 参考链接 https://ask.dcloud.net.cn/article/39531
        const platform = plus.os.name; //  Android/iOS
        let hasBaiduMap = plus.runtime.isApplicationExist({
            pname: 'com.baidu.BaiduMap',
            action: 'baidumap://'
        });
        console.log("hasBaiduMap：", hasBaiduMap);
        let hasAmap = plus.runtime.isApplicationExist({
            pname: 'com.autonavi.minimap',
            action: 'androidamap://'
        });
        console.log("hasAmap", hasAmap);
        let hasQQmap = plus.runtime.isApplicationExist({
            pname: 'com.tencent.map',
            action: 'qqmap://'
        });
        console.log("hasQQmap", hasQQmap);
        if (hasAmap && mapData.urlAppAmap) {
            // 打开高德地图参数说明  https://developer.amap.com/api/amap-mobile/guide/android/marker
            list.push('高德地图');
            if (platform == 'Android') {
                urlList['高德地图'] = `androidamap://viewMap?${mapData.urlAppAmap}`;
            } else if (platform == 'iOS') {
                urlList['高德地图'] = `iosamap://viewMap?${mapData.urlAppAmap}`;
            }
        }
        if (hasBaiduMap && mapData.urlAppBmap) {
            // 打开百度地图参数说明  https://lbsyun.baidu.com/index.php?title=uri/api/android#service-page-anchor8  2.2.2 自定义打点
            list.push('百度地图');
            urlList['百度地图'] = `baidumap://map/marker?${mapData.urlAppBmap}`;
        }
        if (hasQQmap && mapData.urlAppQQmap) {
            // 打开腾讯地图参数说明  https://lbs.qq.com/webApi/uriV1/uriGuide/uriMobileMarker
            list.push('腾讯地图');
            urlList['腾讯地图'] = `qqmap://map/marker?${mapData.urlAppQQmap}`
        }
        if (list.length == 0) {
            that.toast('暂无可打开地图');
            return;
        }


        // #endif
        // #ifdef H5
        if (mapData.urlH5Amap) {
            list.push('高德地图');
            urlList['高德地图'] = mapData.urlH5Amap;
        }
        if (mapData.urlH5Bmap) {
            list.push('百度地图');
            urlList['百度地图'] = mapData.urlH5Bmap;
        }
        if (mapData.urlH5QQmap) {
            list.push('腾讯地图');
            urlList['腾讯地图'] = mapData.urlH5QQmap;
        }
        if (list.length == 0) {
            that.toast('暂无可打开地图');
            return;
        }
        // #endif

        // console.log(list);

        uni.showActionSheet({
            itemList: list,
            success: function (res) {
                // console.log(urlList[list[res.tapIndex]]);
                // #ifdef APP-PLUS
                plus.runtime.openURL(urlList[list[res.tapIndex]]);
                // #endif
                // #ifdef H5
                window.location.href = urlList[list[res.tapIndex]];
                // #endif
            },
            fail: function (res) {
                // console.log(res.errMsg);
                // that.toast(res.errMsg);
            }
        });
    },
    toCall(tel) {
        uni.makePhoneCall({
            phoneNumber: tel //仅为示例
        });
    },
    toCopy(text) {
        const that = this;
        uni.setClipboardData({
            data: text,
            showToast: false,
            success: function () {
                that.toast('复制成功');
            }
        });
    },
    toPreviewImage(current, urls) {
        uni.previewImage({
            current: current,
            urls: urls
        });
    },
    toOpenExternalPage(data) {
        if (data && data.url) {
            this.openWin('/pages/other/external_page', data);
        }
    },
    //对象转字符串  格式 ： a=1&b=1
    urlParam(data) {
        let url = ''
        for (var k in data) {
            let value = data[k] !== undefined ? data[k] : ''
            url += '&' + k + '=' + encodeURIComponent(value)
        }
        return url ? url.substring(1) : ''
    },
    //获取当前页面url中的参数
    getUrlParam(key) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
        var result = window.location.search.substr(1).match(reg);
        return result ? decodeURIComponent(result[2]) : '';
    },
    //拨打电话
    toCall(tel) {
        uni.makePhoneCall({
            phoneNumber: tel
        });
    },
    //替换mobile
    replaceMobile(mobile) {
        if (mobile.toString().length > 10) {
            return mobile.toString().replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
        } else {
            return '';
        }
    },
    //替换身份证号
    replaceIdcard(str) {
        if (str.length > 17) {
            // return str.replace(/(?<=\d{4})\d+(?=[\dX]{3})/, "***********");
            return str.replace(/(\d{3})\d{11}(\d{4})/, '$1***********$2');
        } else {
            return '';
        }
    },
    //手机号码验证
    ValidateMobile(mobile) {
        // var isPhone = /^[1][3,4,5,7,8][0-9]{9}$/; //手机号码
        var isPhone = /^[1][0-9]{10}$/;
        //手机号码
        var isMob = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
        // 座机格式
        if (isMob.test(mobile) || isPhone.test(mobile)) {
            return true;
        } else {
            return false;
        }
    },
    //数字验证
    ValidateNum(num) {
        let isNum = /^[0-9]*$/;
        // var isNum = /^[0-9]$/;
        // 座机格式
        if (isNum.test(num)) {
            return true;
        } else {
            return false;
        }
    },
    //必须有数字+字母 验证
    ValidateNumAndLetter(txt) {
        let reg = new RegExp(/^(?![^a-zA-Z]+$)(?!\D+$)/);
        // 座机格式
        if (reg.test(txt)) {
            return true;
        } else {
            return false;
        }
    },
    //获取时间
    getTimeTxt(type) {
        // date.getYear(); //获取当前年份(2位)
        // date.getFullYear(); //获取完整的年份(4位)
        // date.getMonth(); //获取当前月份(0-11,0代表1月)
        // date.getDate(); //获取当前日(1-31)
        // date.getDay(); //获取当前星期X(0-6,0代表星期天)
        // date.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
        // date.getHours(); //获取当前小时数(0-23)
        // date.getMinutes(); //获取当前分钟数(0-59)
        // date.getSeconds(); //获取当前秒数(0-59)
        // date.getMilliseconds(); //获取当前毫秒数(0-999)
        // date.toLocaleDateString(); //获取当前日期
        // var mytime = date.toLocaleTimeString(); //获取当前时间
        // date.toLocaleString(); //获取日期与时间

        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        month = month < 10 ? '0' + month : month;
        let day = date.getDate();
        day = day < 10 ? '0' + day : day;
        let hours = date.getHours();
        hours = hours < 10 ? '0' + hours : hours;
        let minutes = date.getMinutes();
        minutes = minutes < 10 ? '0' + minutes : minutes;
        let seconds = date.getSeconds();
        seconds = seconds < 10 ? '0' + seconds : seconds;
        switch (type) {
            case 'Y-M-D':
                return year + '-' + month + '-' + day;
                break;
            case 'YMD':
                return year + month + day;
                break;
            case 'Y-M-D H:m:s':
                return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
                break;
        }
    },
    //处理性别
    dealSex(sex) {
        switch (sex) {
            case 1:
                return '男';
            case 2:
                return '女';
            default:
                return '';
        }
    },
    //图片转base64
    imgToBase64(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
        var dataURL = canvas.toDataURL("image/" + ext);
        return dataURL;
    },
    //将图片压缩成为base64
    comprossImage: async function (imgSrc, maxWidth) {
        if (!imgSrc) return 0;
        return new Promise((resolve, reject) => {
            maxWidth = maxWidth || 500; /*默认压缩成500宽*/
            uni.getImageInfo({
                src: imgSrc,
                success(res) {
                    // if (res.width <= maxWidth) { /*太小的图片就不压缩了*/
                    // 	resolve(imgSrc);
                    // 	return;
                    // }
                    let img = new Image();
                    img.src = res.path;
                    img.onload = () => {
                        let canvas = document.createElement('canvas');
                        let scale = res.width / res.height;
                        let ctx = canvas.getContext('2d');
                        canvas.width = maxWidth;
                        canvas.height = maxWidth / scale;
                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                        /* 默认图片质量为0.7 */
                        var quality = 0.7;
                        /* 回调函数返回base64的值 */
                        var base64 = canvas.toDataURL('image/jpeg', quality);
                        resolve(base64);
                    }

                }
            });
        })
    },
    // 获取本地视频信息
    getLocalVideoInfo(file) {
        return new Promise((resolve, reject) => {
            uni.getVideoInfo({
                src: file,
                success: function (res) {
                    // console.log(res);
                    resolve({
                        code: 0,
                        msg: '获取视频信息成功',
                        data: res
                    });
                },
                fail: function (err) {
                    // console.log(err);
                    resolve({
                        code: 1,
                        msg: '获取视频信息失败，请稍后再试'
                    });
                },
            })
        })
    },
    // 获取本地图片信息
    getLocalImageInfo(file) {
        return new Promise((resolve, reject) => {
            uni.getImageInfo({
                src: file,
                success: function (res) {
                    // console.log(res);
                    resolve({
                        code: 0,
                        msg: '获取图片信息成功',
                        data: res
                    });
                },
                fail: function (err) {
                    // console.log(err);
                    resolve({
                        code: 1,
                        msg: '获取图片信息失败，请稍后再试'
                    });
                },
            })
        })
    },
    // 获取系统信息
    getSystemInfo(file) {
        return new Promise((resolve, reject) => {
            uni.getSystemInfo({
                success: function (res) {
                    resolve({
                        code: 0,
                        msg: '获取系统信息成功',
                        data: res
                    });
                },
                fail: function (err) {
                    // console.log(err);
                    resolve({
                        code: 1,
                        msg: '获取系统信息失败，请稍后再试'
                    });
                },
            });
        })
    },
    downloadFile(url) {
        return new Promise((resolve, reject) => {
            uni.downloadFile({
                url: url,
                success: (res) => {
                    if (res.statusCode === 200) {
                        resolve({
                            code: 0,
                            msg: '下载成功',
                            data: res.tempFilePath
                        });
                    } else {
                        resolve({
                            code: 1,
                            msg: '下载失败，请稍后再试'
                        });
                    }
                },
                fail(err) {
                    resolve({
                        code: 1,
                        msg: '下载失败，请稍后再试'
                    });
                }
            });
        })
    }
};